import 'dart:convert';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:private_journey/States.dart';
import 'package:private_journey/pages/AddNewIconPage.dart';
import 'package:private_journey/pages/trending.dart';
import 'package:private_journey/services/DbService.dart';
import 'package:private_journey/services/FileService.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' as shadcn;
import 'package:signals/signals_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

class LinkItemComponent extends StatefulWidget {
  final LinkInfo e;

  LinkItemComponent({super.key, required this.e});

  @override
  State<LinkItemComponent> createState() => _LinkItemComponentState();
}

class _LinkItemComponentState extends State<LinkItemComponent> {
  Widget buildIcon(LinkInfo e) {
    if (FileService.isSvg(e.icon)) {
      var icon = base64Decode(e.icon);
      return SvgPicture.memory(icon, height: 50, width: 50);
    }
    if (FileService.isPng(e.icon)) {
      var icon = base64Decode(e.icon);
      return Image.memory(icon, height: 50, width: 50);
    }
    if (FileService.isIco(e.icon)) {
      var icon = base64Decode(e.icon);
      return Image.memory(icon, height: 50, width: 50);
    }
    return Container();
  }

  void deleteFromDb(LinkInfo e) async {
    DbService dbService = DbService();
    var db = await dbService.database;
    db.rawDelete('delete from my_sites where id = ?', [e.id]);
    linkInfos.value = [...linkInfos.value..remove(e)];
  }

  List<shadcn.MenuItem> menuList() {
    return [
      shadcn.MenuButton(
        onPressed: (c) {
          deleteFromDb(widget.e);
        },
        trailing: shadcn.MenuShortcut(
          activator: SingleActivator(
            LogicalKeyboardKey.bracketLeft,
            control: true,
          ),
        ),
        child: Text('删除'),
      ),
      shadcn.MenuButton(
        onPressed: (c) {
          shadcn.showDialog(
            context: c,
            builder: (context) {
              return AddNewIconPage(e: widget.e);
            },
          );
        },
        trailing: shadcn.MenuShortcut(
          activator: SingleActivator(LogicalKeyboardKey.comma, control: true),
        ),
        child: Text('编辑'),
      ),
    ];
  }

  late Signal<int> latecy;

  void measureLatecy(String url) {
    var s = DateTime.now();
    var dio = Dio();
    dio.get(url).then((value) {
      var e = DateTime.now();
      latecy.value = e.difference(s).inMilliseconds;
    });
  }

  @override
  void initState() {
    super.initState();
    latecy = Signal<int>(0);
  }

  @override
  void dispose() {
    latecy.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return shadcn.ContextMenu(
      behavior: HitTestBehavior.opaque, // 修改为 opaque 阻止事件冒泡
      items: menuList(),
      child: shadcn.HoverCard(
        hoverBuilder: (BuildContext context) {
          measureLatecy(widget.e.url);
          return shadcn.SurfaceCard(
            child: Watch((context) {
              return shadcn.Basic(
                leading: Icon(Icons.network_wifi_sharp),
                title: Text('@flutter'),
                content: Text(
                  'the url is ${widget.e.url}\'s latecy is ${latecy.value} ms',
                ),
              );
            }),
          ).sized(width: 300);
        },
        child: MouseRegion(
          cursor: SystemMouseCursors.click,
          child: shadcn.GestureDetector(
            onTap: () {
              launchUrl(Uri.parse(widget.e.url));
            },
            child: shadcn.Container(
              key: ValueKey(widget.e.id),
              width: 100,
              height: 100,
              padding: const shadcn.EdgeInsets.all(10),

              decoration: shadcn.BoxDecoration(
                borderRadius: shadcn.BorderRadius.circular(10),
                border: Border.all(color: Colors.pink, width: 1),
                color: Colors.white.withAlpha(100),
              ),
              child: Column(
                children: [
                  buildIcon(widget.e),
                  AutoSizeText(widget.e.text, maxLines: 1),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
